package com.mes.eventhandler;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.event.Observes;

import org.apache.log4j.Logger;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;

import com.mes.quality.data.EmesqQualityROR;

public class EmesqQualityRouteOprRelationEventHandler extends EntityPersistenceEventObserver {

	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EmesqQualityROR.ENTITY_NAME) };

	protected Logger logger = Logger.getLogger(this.getClass());

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}
	
	private void throwMessage(String message){
		String language = OBContext.getOBContext().getLanguage().getLanguage();
		ConnectionProvider conn = new DalConnectionProvider(false);
		throw new OBException(Utility.messageBD(conn, message, language));
	}
	
	public void onSave(@Observes EntityNewEvent event) {
	    if (!isValidEvent(event)) {
	      return;
	    }
	    final EmesqQualityROR emesqQualityROR = (EmesqQualityROR) event.getTargetInstance();
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(emesqQualityROR.getEmesProcessOpr());
		paramList.add(emesqQualityROR.getEmesqInspectionGroup());
		//查询该code在哪些机构中存在]
		
		List<EmesqQualityROR> list = OBDal.getInstance().createQuery(EmesqQualityROR.class, 
				"emesProcessOpr=? and emesqInspectionGroup=?", paramList).list();
		if(list.size() > 0){
			throwMessage("同一个工序，只能与一个检验模型组关联");
		}
	}

	public void onUpdate(@Observes EntityUpdateEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		final EmesqQualityROR emesqQualityROR = (EmesqQualityROR) event.getTargetInstance();
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(emesqQualityROR.getEmesProcessOpr());
		paramList.add(emesqQualityROR.getEmesqInspectionGroup());
		paramList.add(emesqQualityROR.getId());
		//查询该code在哪些机构中存在]
		
		List<EmesqQualityROR> list = OBDal.getInstance().createQuery(EmesqQualityROR.class, 
				"emesProcessOpr=? and emesqInspectionGroup=? and id<>?", paramList).list();
		if(list.size() >= 1){
			throwMessage("同一个工序，只能与一个检验模型组关联");
		}
	}

}
